using System;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.UI.WebControls;
using System.Security;
using System.Security.Principal;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebControls;

namespace Starznet.SharePoint.SPDAT.ApplicationPages.Administration
{
    public class ManageMembershipPage : StarznetBaseAdministrationPage
    {
        protected WebApplicationSelector Selector;

        protected InputFormTextBox TxtDefaultMembershipProvider;
        protected InputFormCheckBox ChkEnablePassRetrieval;
        protected InputFormCheckBox ChkEnablePassReset;
        protected InputFormCheckBox ChkRequireQA;
        protected InputFormTextBox TxtApplicationName;
        protected InputFormCheckBox ChkRequireUniqueEmail;
        protected RadioButton rdoPassFormat_Hashed;
        protected RadioButton rdoPassFormat_Clear;
        protected RadioButton rdoPassFormat_Encrypted;
        protected InputFormTextBox TxtMaxInvalidPassAttempts;
        protected InputFormTextBox TxtMinReqPassLength;
        protected InputFormTextBox TxtMinReqNonAlphaChars;
        protected InputFormTextBox TxtPasswordRegEx;
        protected DropDownList DdlConnString;
        protected InputFormTextBox TxtPassWindow;
        protected Label LblWebApp;
        protected Panel PnlOtherConn;
        protected InputFormTextBox TxtOtherConn;

        private String sWebApp;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            sWebApp = Request.QueryString["wapp"];

            DdlConnString.SelectedIndexChanged += new EventHandler(DdlConnString_SelectedIndexChanged);

            if(!IsPostBack)
                this.LoadMembershipSettings();
        }

        void DdlConnString_SelectedIndexChanged(object sender, EventArgs e)
        {
            PnlOtherConn.Visible = (DdlConnString.SelectedValue == string.Empty);
        }

        private void LoadMembershipSettings()
        {
            IntPtr oUserToken = WindowsIdentity.GetCurrent().Token;

            System.Configuration.Configuration oConfig =
                WebConfigurationManager.OpenWebConfiguration("/", sWebApp, "", Environment.MachineName, oUserToken);
            MembershipSection oMemberSection = (MembershipSection)oConfig.GetSection("system.web/membership");
            ProviderSettings oSettings = oMemberSection.Providers[oMemberSection.DefaultProvider];

            //Populate the connection string dropdown
            ListItem oItem;
            foreach (ConnectionStringSettings oConn in oConfig.ConnectionStrings.ConnectionStrings)
            {
                oItem = new ListItem(oConn.Name, oConn.Name);
                this.DdlConnString.Items.Add(oItem);
            }
            this.DdlConnString.Items.Add(new ListItem("Specify Other", string.Empty));
            this.DdlConnString.SelectedValue = oSettings.Parameters["connectionStringName"].ToString();
            this.LblWebApp.Text = sWebApp;

            this.TxtDefaultMembershipProvider.Text = oMemberSection.DefaultProvider;
            this.TxtApplicationName.Text = oSettings.Parameters["applicationName"].ToString();
            this.ChkEnablePassRetrieval.Checked = bool.Parse(oSettings.Parameters["enablePasswordRetrieval"].ToString());
            this.ChkEnablePassReset.Checked = bool.Parse(oSettings.Parameters["enablePasswordReset"].ToString());
            this.ChkRequireQA.Checked = bool.Parse(oSettings.Parameters["requiresQuestionAndAnswer"].ToString());
            this.ChkRequireUniqueEmail.Checked = bool.Parse(oSettings.Parameters["requiresUniqueEmail"].ToString());

            switch (oSettings.Parameters["passwordFormat"].ToString().ToLower())
            {
                case "hashed":
                    this.rdoPassFormat_Hashed.Checked = true;
                    break;
                case "clear":
                    this.rdoPassFormat_Clear.Checked = true;
                    break;
                case "encrypted":
                    this.rdoPassFormat_Encrypted.Checked = true;
                    break;
            }

            this.TxtMaxInvalidPassAttempts.Text = oSettings.Parameters["maxInvalidPasswordAttempts"].ToString();
            this.TxtMinReqNonAlphaChars.Text = oSettings.Parameters["minRequiredNonalphanumericCharacters"].ToString();
            this.TxtMinReqPassLength.Text = oSettings.Parameters["minRequiredPasswordLength"].ToString();
            this.TxtPasswordRegEx.Text = oSettings.Parameters["passwordStrengthRegularExpression"].ToString();
            this.TxtPassWindow.Text = oSettings.Parameters["passwordAttemptWindow"].ToString();

        }

        protected void BtnAdd_Click(object sender, EventArgs e)
        {
            IntPtr oUserToken = WindowsIdentity.GetCurrent().Token;

            System.Configuration.Configuration oConfig =
                WebConfigurationManager.OpenWebConfiguration("/", sWebApp, "", Environment.MachineName, oUserToken);
            MembershipSection oMemberSection = (MembershipSection)oConfig.GetSection("system.web/membership");
            ProviderSettings oSettings = oMemberSection.Providers[oMemberSection.DefaultProvider];

            if (DdlConnString.SelectedValue == string.Empty)
            {
                //Add a new connection string
                Guid oGuid = Guid.NewGuid();
                ConnectionStringSettings oConnSettings = new ConnectionStringSettings();
                oConnSettings.Name = "SZ_" + oGuid.ToString().Replace("-","");
                oConnSettings.ConnectionString = this.TxtOtherConn.Text;
                oConfig.ConnectionStrings.ConnectionStrings.Add(oConnSettings);

                oSettings.Parameters["connectionStringName"] = oConnSettings.Name;
            }
            else
                oSettings.Parameters["connectionStringName"] = this.DdlConnString.SelectedValue;
            
            oSettings.Parameters["applicationName"] = this.TxtApplicationName.Text;
            oSettings.Parameters["enablePasswordRetrieval"] = this.ChkEnablePassRetrieval.Checked ? "true" : "false";
            oSettings.Parameters["enablePasswordReset"] = this.ChkEnablePassReset.Checked ? "true" : "false";
            oSettings.Parameters["requiresQuestionAndAnswer"] = this.ChkRequireQA.Checked ? "true" : "false";
            oSettings.Parameters["requiresUniqueEmail"] = this.ChkRequireUniqueEmail.Checked ? "true" : "false";

            if (this.rdoPassFormat_Clear.Checked)
                oSettings.Parameters["passwordFormat"] = "Clear";
            if (this.rdoPassFormat_Encrypted.Checked)
                oSettings.Parameters["passwordFormat"] = "Encrypted";
            if(this.rdoPassFormat_Hashed.Checked)
                oSettings.Parameters["passwordFormat"] = "Hashed";

            oSettings.Parameters["maxInvalidPasswordAttempts"] = this.TxtMaxInvalidPassAttempts.Text;
            oSettings.Parameters["minRequiredNonalphanumericCharacters"] = this.TxtMinReqNonAlphaChars.Text;
            oSettings.Parameters["minRequiredPasswordLength"] = this.TxtMinReqPassLength.Text;
            oSettings.Parameters["passwordStrengthRegularExpression"] = this.TxtPasswordRegEx.Text;
            oSettings.Parameters["passwordAttemptWindow"] = this.TxtPassWindow.Text;

            oConfig.Save();

            Response.Redirect(PageToRedirectOnCancel);
        }

        public override string PageToRedirectOnCancel
        {
            get
            {
                return "MembershipAppList.aspx";
            }
        }
    }
}
